/*
 * Copyright (2025) UCT Ltd. and/or its affiliates
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { hilog } from '@kit.PerformanceAnalysisKit';
import { BigIntToStringConvertor, Columns, ColumnType, Embedded, Entity, RdbDao, RdbDatabase } from 'rdbstore';
import { getDB, Env, SearchParams, DeleteParams } from 'commondb';
//#region Human-Code Preservation

//#endregion Human-Code Preservation
const apiURL: string = Env.CLOUD_API_URL
let _table_name_Dao: RdbDao<_table_name_>;

@Entity({
  tableName: '_table_name_',
  index: [{ name: 'idIndex', columnName: ['id'], unique: true }]
})
//todo:添加响应式状态关联
export class _table_name_ {
  //规范化状态管理
  REPLACE_MODELFIELDS

  toString(): string {
    return JSON.stringify({
REPLACE_MODELTOSTRING    }, null, 2);  // 添加缩进格式化
  }

  static getSelectKey(): SelectKeyItem[] {
    return [
      REPLACE_SELECTKEY    ];
  }

   /**
   * 从JSON字符串创建entity实例
   * @param jsonStr JSON格式的字符串
   * @returns entity实例
   */
  static fromJson(jsonStr: string): _table_name_ {
    try {
      // 将JSON字符串解析为对象
      const jsonData: edit_TableName_Params = JSON.parse(jsonStr);
      const _table_name_Obj = new _table_name_();
      
      // 赋值所有属性
      REPLACE_MODELFROMJSON

      return _table_name_Obj;
    } catch (error) {
      console.error('Failed to convert JSON to _table_name_:', error);
      return new _table_name_();
    }
  }
  //标准API接口
  static async apiGet_TableName_List(page: number, pageSize: number, searchParams?: string | Record<string, string | number | boolean>){
    let db: RdbDatabase  = getDB(Env.DATABASE_UCTOO_NAME);
    let _table_name_Dao: RdbDao<_table_name_> = await db.getDao(_table_name_);
    return db.extension.axiosPlugin?.setDao(_table_name_Dao).api().get(`/api/_table_name_/${pageSize}/${page}`, {
      params: searchParams,
      headers: { 
        'Content-Type': 'application/json;charset=utf-8',
        'Authorization': `Bearer ${AppStorage.get<string>('access_token')}`
      },
      baseURL: apiURL,
      dataKey: '_tableName_s'
    })
  }
  static async  apiGet_TableName_(id: string){
    let db: RdbDatabase  = getDB(Env.DATABASE_UCTOO_NAME);
    let _table_name_Dao: RdbDao<_table_name_> = await db.getDao(_table_name_);
    return db.extension.axiosPlugin?.setDao(_table_name_Dao).api().get(`/api/_table_name_/${id}`, {
      headers: { 
        'Content-Type': 'application/json;charset=utf-8',
        'Authorization': `Bearer ${AppStorage.get<string>('access_token')}`
      },
      baseURL: apiURL,
    })
  }
  static async  apiAdd_TableName_(data: Partial<_TableName_Formated>){
    let db: RdbDatabase  = getDB(Env.DATABASE_UCTOO_NAME);
    let _table_name_Dao: RdbDao<_table_name_> = await db.getDao(_table_name_);
    return db.extension.axiosPlugin?.setDao(_table_name_Dao).api().post('/api/_table_name_/add', data, {
      headers: { 
        'Content-Type': 'application/json;charset=utf-8',
        'Authorization': `Bearer ${AppStorage.get<string>('access_token')}`
      },
      baseURL: apiURL,
    })
  }
  static async  apiEdit_TableName_(data: Partial<edit_TableName_Params>){
    let db: RdbDatabase  = getDB(Env.DATABASE_UCTOO_NAME);
    let _table_name_Dao: RdbDao<_table_name_> = await db.getDao(_table_name_);
    return db.extension.axiosPlugin?.setDao(_table_name_Dao).api().post('/api/_table_name_/edit', data, {
      headers: { 
        'Content-Type': 'application/json;charset=utf-8',
        'Authorization': `Bearer ${AppStorage.get<string>('access_token')}`
      },
      baseURL: apiURL,
    })
  }
  static async  apiDelete_TableName_(data: DeleteParams){
    let db: RdbDatabase  = getDB(Env.DATABASE_UCTOO_NAME);
    let _table_name_Dao: RdbDao<_table_name_> = await db.getDao(_table_name_);
    return db.extension.axiosPlugin?.setDao(_table_name_Dao).api().post('/api/_table_name_/del', data, {
      headers: { 
        'Content-Type': 'application/json;charset=utf-8',
        'Authorization': `Bearer ${AppStorage.get<string>('access_token')}`
      },
      baseURL: apiURL,
    })
  }

  /**
   * Remove empty values from _table_name_
   * @param obj _table_name_ object
   * @returns _table_name_ with non-empty values
   */
  static removeEmpty(obj: _table_name_): Partial<_TableName_Formated> {
    const result: Partial<_TableName_Formated> = {};

    REPLACE_REMOVEEMPTY
    return result;
  }

  /**
   * Remove null values from _table_name_
   * @param obj _table_name_ object
   * @returns _table_name_ with non-null values
   */
  static removeNull(obj: edit_TableName_Params): Partial<edit_TableName_Params> {
    const result: Partial<edit_TableName_Params> = {};

    REPLACE_REMOVENULL
    return result;
  }

//#region Human-Code Preservation

//#endregion Human-Code Preservation
}

export interface _TableName_Formated {
  REPLACE_MODELFORMATED
};
export interface edit_TableName_Params {
  REPLACE_MODELEDITPARAMS
}
export interface _TableName_Response {
  currentPage: number;
  _table_name_s: _table_name_[];
  total: number;
}

/** 链接查询条件 */
interface IdFilter {
  equals?: string;
}

/** 实体查询条件 */
interface _TableName_Filter {
  id?: IdFilter;
}

// 添加查询参数结果接口定义
interface QueryParamsResult extends Record<string, string | number | boolean> {
  sort: string;
  filter: string;
}

/** API查询参数 */
export class _TableName_QueryParams {
  sort: string = '';
  filter: string = '';

  constructor(searchValue?: string) {
    if (searchValue) {
      const _table_name_Filter: _TableName_Filter = {
        id: {
          equals: searchValue
        }
      };
      this.filter = JSON.stringify(_table_name_Filter);
    }
  }

  toQueryParams(): QueryParamsResult {
    const result: QueryParamsResult = {
      sort: this.sort,
      filter: this.filter
    };
    return result;
  }
}

interface SelectKeyItem {
  value: string;
}
//#region Human-Code Preservation

//#endregion Human-Code Preservation